package com.cqhz.quwan.ui.activity

import android.content.Intent
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.cqhz.quwan.APP
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.CouponBean
import com.cqhz.quwan.model.LoginBean
import com.cqhz.quwan.model.PageResultBean
import com.cqhz.quwan.mvp.MyCouponContract
import com.cqhz.quwan.mvp.MyCouponPresenter
import com.cqhz.quwan.service.API
import com.cqhz.quwan.ui.base.GoBackActivity
import com.cqhz.quwan.ui.base.WebViewActivity
import com.cqhz.quwan.util.CommonAdapterHelper
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import kotlinx.android.synthetic.main.activity_my_coupon.*
import me.militch.quickcore.core.HasDaggerInject
import javax.inject.Inject

/**
 * 我的红包
 * Created by Guojing on 2018/12/12.
 */
class MyCouponActivity : GoBackActivity(), MyCouponContract.View, HasDaggerInject<ActivityInject> {

    @Inject
    lateinit var myCouponPresenter: MyCouponPresenter
    private var loginInfo: LoginBean? = null
    private var titles = arrayOf("未使用", "待派发", "已失效")
    private var pages = ArrayList<View>()
    private var holders = ArrayList<PageViewHolder>()
    private var adapters = ArrayList<BaseQuickAdapter<*, *>>()
    private var coupons = ArrayList<ArrayList<CouponBean>>()

    override fun inject(t: ActivityInject?) {
        t?.inject(this)
    }

    override fun titleBarText(): String? {
        return "我的红包"
    }

    override fun layout(): Int {
        return R.layout.activity_my_coupon
    }

    override fun initView() {
        myCouponPresenter.attachView(this)
        if (APP.get()!!.loginInfo != null) {
            loginInfo = APP.get()!!.loginInfo
        }

        // 初始化页面元素和相应数据以及适配器
        for (i in 0 until titles.size) {
            initAdapter(i)
        }

        initPager()
        // 加载数据
        refreshCurrentPage()

        setTitleBarRightText("使用规则") {
            val intent = Intent(this, WebViewActivity::class.java)
            intent.putExtra(KeyContract.Title, "使用规则")
            val url = "${API.couponUseRule}"
            intent.putExtra(KeyContract.Url, url)
            startActivity(intent)
        }
    }

    /**
     * 初始化页面
     */
    private fun initPager() {
        vp_content.adapter = object : PagerAdapter() {
            override fun getCount(): Int {
                return pages.size
            }

            override fun isViewFromObject(view: View, `object`: Any): Boolean {
                return view === `object`
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                container.removeView(pages[position])
            }

            override fun instantiateItem(container: ViewGroup, position: Int): Any {
                var view = pages[position]
                var parent = view.parent as? ViewGroup
                parent?.removeAllViews()
                container.addView(view)
                return view
            }
        }
        st_tab.setViewPager(vp_content, titles)
        vp_content.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

            override fun onPageSelected(position: Int) {
                if (coupons[position].size <= 0) {
                    refreshCurrentPage()
                }
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
    }

    /**
     * 初始化列表适配器
     */
    private fun initAdapter(position: Int) {
        // 当前页面的布局
        var pageView = LayoutInflater.from(this).inflate(R.layout.layout_page, vp_content, false) as View
        var holder = PageViewHolder(pageView)

        // 当前页面列表的空布局
        var emptyView = LayoutInflater.from(this).inflate(R.layout.layout_none, holder.rvContent.parent as? ViewGroup, false) as View
        var ivNone = emptyView.findViewById(R.id.iv_none) as ImageView
        ivNone.setImageResource(0)

        // 当前页面列表的数据和适配器
        var couponList = ArrayList<CouponBean>()
        var couponListAdapter = CommonAdapterHelper.getCouponListAdapter(couponList, position)
        couponListAdapter!!.emptyView = emptyView

        // 当前页面列表适配器的事件
        holder.rvContent.layoutManager = LinearLayoutManager(this)
        holder.rvContent.adapter = couponListAdapter
        couponListAdapter.setOnLoadMoreListener({
            var currentPage = vp_content.currentItem
            if (coupons[currentPage].size > 0) {
                if (coupons[currentPage].size % KeyContract.pageSize == 0) {
                    var pageNo = coupons[currentPage].size / KeyContract.pageSize + 1
                    holders[currentPage].refreshLayout.isEnableRefresh = false
                    myCouponPresenter.getCouponList(loginInfo!!.userId!!.toLong(), currentPage, pageNo, KeyContract.pageSize)
                } else {
                    adapters[currentPage].loadMoreEnd()
                }
            } else {
                holders[currentPage].refreshLayout.isEnableRefresh = false
                myCouponPresenter.getCouponList(loginInfo!!.userId!!.toLong(), currentPage, 1, KeyContract.pageSize)
            }
        }, holder.rvContent)
        holder.rvContent.addOnItemTouchListener(object : OnItemClickListener() {
            override fun onSimpleItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
                var currentPage = vp_content.currentItem
                val item = adapters[currentPage].getItem(position) as CouponBean
                if (item.status == 0) {
                    val intent = Intent(context(), FootballLotteryActivity::class.java)
                    intent.putExtra(KeyContract.LotteryId, "21")
                    intent.putExtra(KeyContract.Position, 0)
                    startActivity(intent)
                }
            }
        })
        // 刷新
        holder.refreshLayout.setOnRefreshListener { refreshCurrentPage() }

        // 将当前的页面、列表控件、数据列表、适配器加入相应的列表
        pages.add(pageView)
        holders.add(holder)
        coupons.add(couponList)
        adapters.add(couponListAdapter)
    }

    /**
     * 刷新当前页面
     */
    private fun refreshCurrentPage() {
        var currentPage = vp_content.currentItem
        myCouponPresenter.getCouponList(loginInfo!!.userId!!.toLong(), currentPage, 1, KeyContract.pageSize)
    }

    override fun loadCouponList(currentPage: Int, pageNo: Int, pageResultBean: PageResultBean<CouponBean>) {
        if (pageNo == 1) {
            coupons[currentPage].clear()
            adapters[currentPage].setEnableLoadMore(true)
            if (holders[currentPage].refreshLayout.state.isHeader) {
                holders[currentPage].refreshLayout.finishRefresh()
            }
        }

        if (pageResultBean.records.isNotEmpty()) {
            coupons[currentPage].addAll(pageResultBean.records)
        }

        if (pageResultBean.total > coupons[currentPage].size) {
            adapters[currentPage].loadMoreComplete()
        } else {
            adapters[currentPage].loadMoreEnd()
        }

        adapters[currentPage].notifyDataSetChanged()
        holders[currentPage].refreshLayout.isEnableRefresh = true
    }

    internal class PageViewHolder(view: View) {
        var rvContent = view.findViewById(R.id.rv_content) as RecyclerView
        var refreshLayout = view.findViewById(R.id.refreshLayout) as SmartRefreshLayout
    }

    override fun onDestroy() {
        super.onDestroy()
        myCouponPresenter.detachView()
    }
}
